package com.jeejio.train.service.impl;

import com.jeejio.train.dao.LecturerMapper;
import com.jeejio.train.entity.Lecturer;
import com.jeejio.train.service.LecturerService;
import com.jeejio.train.util.IConstant;
import com.jeejio.train.util.MD5;
import com.jeejio.train.util.UserException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.NoSuchAlgorithmException;
import java.util.List;

@Service
@Transactional
public class LecturerServiceImpl implements LecturerService {

    @Autowired
    private LecturerMapper lecturerMapper = null;

    @Override
    public Lecturer login(String name, String pwd) throws UserException {
        List<Lecturer> lecturerList = lecturerMapper.selectByLoginName(name);
        if (lecturerList.size() == 0) {
            return null;
        }
        Lecturer lecturer = lecturerList.get(0);
        // Determine whether initialization password is required.
        if ((!StringUtils.isEmpty(lecturer.getCipherKey()))
                && StringUtils.isEmpty(lecturer.getSalt())) { // The user is need initialization password.
            try {
                MD5.Result result = MD5.salt32(lecturer.getCipherKey());
                lecturer.setCipherKey(result.hash);
                lecturer.setSalt(result.salt);
                lecturerMapper.updateByPrimaryKey(lecturer);
                return lecturer;
            } catch (NoSuchAlgorithmException e) {
                UserException userException = new UserException(
                        IConstant.E_LOGIN, "用户密码初始化失败！");
                userException.initCause(e);
                throw userException;
            }
        }

        try {
            MD5.Result result = MD5.calc32(pwd);
            result = MD5.calc32(result.hash + lecturer.getSalt());
            if (result.hash.equals(lecturer.getCipherKey())) {
                return lecturer;
            }
        } catch (NoSuchAlgorithmException e) {
            UserException userException = new UserException(IConstant.E_LOGIN, "登录失败！");
            userException.initCause(e);
            throw userException;
        }
        return null;
    }
}
